package com.xykj.enterprise.wechat.client;

import com.ydn.appserver.ClientConfiguration;
import com.ydn.appserver.MinaAppClient;
import com.ydn.appserver.Request;
import com.ydn.appserver.Response;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;
import java.util.Map;

/**
 * @author Feng Chen
 */
@Component
@Slf4j
public class ExtClient {

    @Value("${ext.addrs}")
    private String addrs;

    @Value("${ext.maxConn:64}")
    private int maxConn;

    @Value("${ext.coTimeout:3000}")
    private int coTimeout;

    @Value("${ext.soTimeout:3000}")
    private int soTimeout;

    private MinaAppClient delegate;

    @PostConstruct
    public void start() {
        ClientConfiguration configuration = new ClientConfiguration();
        configuration.setServerAddressesString(addrs);
        configuration.setMaxConnectionsPerServer(maxConn);
        configuration.setSocketConnTimeoutSec(coTimeout);
        configuration.setSocketDataTimeoutSec(soTimeout);
        delegate = new MinaAppClient(configuration);
    }

    @PreDestroy
    public void close() {
        if (delegate != null) {
            delegate.close();
        }
    }

    public Response send(Request request) {
        return delegate.send(request);
    }

    public  <T> T get(String action, Map<String, Object> params, Class<T> type) {
        Request request = new Request(action);
        if (params != null) {
            for (Map.Entry<String, Object> param : params.entrySet()) {
                Object value = param.getValue();
                if (value != null) {
                    request.setParameter(param.getKey(), String.valueOf(value));
                }
            }
        }
        Response response = delegate.send(request);
        if (response.isSuccess()) {
            log.debug(response.getOriginalJson());
            return response.getObject("data", type);
        }
        return null;
    }


}
